package business

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/gookit/event"
	"vueBasic/app/admin/filter"
	"vueBasic/app/common/model"
	"vueBasic/extend/conv"
	"vueBasic/extend/jwt"
	"vueBasic/extend/utils"
)

var LoginB = new(LoginBus)

type LoginBus struct{}

func (*LoginBus) DoLogin(req *filter.AdminLoginReq, c *gin.Context) (string, error) {
	userInfo, err := model.AdminUserM.GetAdminUserInfoByUsername(req.User)
	if err != nil {
		return "", err
	}
	//校验密码是否正确
	if !conv.EqualsPassword(req.Pwd, userInfo.Password) {
		return "", errors.New("密码错误！")
	}
	//jwt生成token以及保存token到session
	token, jwtErr := jwt.NewJWT("admin").CreateToken(userInfo)
	if jwtErr != nil {
		return "", errors.New("密码token生成失败")
	}
	//更新登录时间
	data := make(map[string]interface{}, 0)
	data["id"] = userInfo.Id
	data["last_login_time"] = conv.NowUnix()
	model.AdminUserM.UpdateExt(data)
	//保存登录日志（可以使用github.com/gookit/event包做一个事件监听）
	event.MustFire("adminLoginEvent", event.M{
		"user":   userInfo.Username,
		"token":  token,
		"handle": c,
	})
	//将token保存到缓存中
	//1、redis适用于前后分离
	//cache.New().Set("admin_token", token, 86400*time.Second)

	//2、session适用内嵌页面项目
	utils.SetSession("userToken", token, c)
	return userInfo.Nickname, nil
}
